const Koa = require('koa')
const path = require('path')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const session = require("koa-session2")
const cors = require('koa2-cors')
const redisStore = require("./config/redisStore")
const rest = require('./rest')
const controls = require('./config/controller')()
// error handler
onerror(app)

// middlewares
app.use(bodyparser({
    enableTypes: ['json', 'form', 'text']
}))
app.use(logger())

app.use(views(__dirname + './views', {
    extension: 'ejs'
}))

// cors
app.use(cors({
    origin: 'http://localhost:3000',
    maxAge: 5,
    credentials: true,
    allowMethods: ['GET', 'POST', 'OPTIONS'],
    allowHeaders: ['Content-Type', 'Authorization', 'Accept']
}))

// logger
app.use(async (ctx, next) => {
    const start = new Date()
    await next()
    const ms = new Date() - start
    console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})

// session
app.use(session({
    store: new redisStore()
}))

// rest
app.use(rest.restify())

// routes
app.use(controls.routes(), controls.allowedMethods())

// error-handling
app.on('error', (err, ctx) => {
    console.error('server error', err, ctx)
});

module.exports = app
